//
//  AppPayVC.swift
//  letuofu
//
//  Created by WH-JS on 2020/3/3.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import SwiftyStoreKit
import MBProgressHUD

class AppPayVC: BaseViewControllerWithHeader,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    var headBackView = UIView()
    var colltionView : UICollectionView?
    let dataList : [[String: Any?]] = [["title": "6元","subtitle": "6元兑换120积分。","PID": "com.51camel.6yuan","jifen": 120],
                                       ["title": "12元","subtitle": "12元兑换240积分。","PID": "com.51camel.12yuan","jifen": 240],
                                       ["title": "25元","subtitle": "25元兑换500积分。","PID": "com.51camel.25yuan","jifen": 500],
                                       ["title": "50元","subtitle": "50元兑换1000积分。","PID": "com.51camel.50yuan","jifen": 1000],
                                       ["title": "98元","subtitle": "98元兑换1960积分。","PID": "com.51camel.90yuan","jifen": 1960]]
    
    let labMoney = UILabel()
    let labSubtitle = UILabel()
    
    var curProduct = [String: Any?]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    
}


// MARK:- UI
extension AppPayVC {
    func setupUI() {
        headTitle.text = "预存款"
        headTitle.textColor = .white
        headView.backgroundColor = .clear
        
        safeView.insertSubview(headBackView, at: 0)
        headBackView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(200)
        }
        headBackView.drawImage(named: "bg_header") { (make) in
            make.left.right.top.bottom.equalToSuperview()
        }.contentMode = .scaleAspectFill
        headBackView.drawLabel(label: labSubtitle, text: "预存款余额（积分）", fontSize: 15, textColor: .white) { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-40)
        }
        headBackView.drawLabel(label: labMoney, text: "0.00", fontSize: 29, textColor: .white) { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-70)
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .init(top: 30, left: 10, bottom: 0, right: 10)
        colltionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        colltionView!.register(AppPayCell.self, forCellWithReuseIdentifier:"cell")
        colltionView?.allowsMultipleSelection = false
        colltionView?.delegate = self;
        colltionView?.dataSource = self;
        colltionView?.backgroundColor = .white
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: 100, height: 65)
        self.safeView.addSubview(colltionView!)
        colltionView?.snp.makeConstraints { (make) in
            make.top.equalTo(headBackView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-100)
        }
        
        let btn = safeView.drawButton(title: "充值", titleColor: .white, fontSize: 15) { (make) in
            make.top.equalTo(colltionView!.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(35)
        }
        btn.backgroundColor = .orange
        btn.layer.cornerRadius = 7
        btn.addTarget(self, action: #selector(onOKButtonClick(button:)), for: .touchUpInside)
    }
}


// MARK:- 事件
extension AppPayVC {
        //获取内购项目列表
    func getList(PID: String) {
            SwiftyStoreKit.retrieveProductsInfo([PID]) { result in
                if let product = result.retrievedProducts.first {
                    let priceString = product.localizedPrice!
                    print("Product: \(product.localizedDescription), price: \(priceString)")
                    self.payByID(ProductID: PID)
                } else if let invalidProductId = result.invalidProductIDs.first {
                    print("Invalid product identifier: \(invalidProductId)")
                    MBProgressHUD.hideOrDecrease()
                } else {
                    print("Error: \(String(describing: result.error))")
                    MBProgressHUD.hideOrDecrease()
                }
            }
        }
        
        //通过id购买
        func payByID(ProductID : String) {
            SwiftyStoreKit.purchaseProduct(ProductID, atomically: true) { result in
                switch result {
                case .success(let purchase):
                    if purchase.needsFinishTransaction {
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                    
                    // 正式验证
//                    #if DEBUG // 判断是否在测试环境下
//                    self.verifyReceipt(service: .sandbox)
//                    #else
                    self.verifyReceipt(service: .production)
//                    #endif
                    print("Purchase Success: \(purchase.productId)")
                case .error(let error):
                    MBProgressHUD.hideOrDecrease()
                    switch error.code {
                    case .unknown: print("Unknown error. Please contact support")
                    case .clientInvalid: print("Not allowed to make the payment")
                    case .paymentCancelled: break
                    case .paymentInvalid: print("The purchase identifier was invalid")
                    case .paymentNotAllowed: print("The device is not allowed to make the payment")
                    case .storeProductNotAvailable: print("The product is not available in the current storefront")
                    case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
                    case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
                    case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
                    case .privacyAcknowledgementRequired:
                        break
                    case .unauthorizedRequestData:
                        break
                    case .invalidOfferIdentifier:
                        break
                    case .invalidSignature:
                        break
                    case .missingOfferParams:
                        break
                    case .invalidOfferPrice:
                        break
                    @unknown default:
                        break
                    }
                }
            }
        }
        
        //取回收据
        func fetchReceipt() {
            SwiftyStoreKit.fetchReceipt(forceRefresh: true) { result in
                switch result {
                case .success(let receiptData):
                    let encryptedReceipt = receiptData.base64EncodedString(options: [])
                    print("Fetch receipt success:\n\(encryptedReceipt)")
                case .error(let error):
                    print("Fetch receipt failed: \(error)")
                }
            }
        }
        
    func verifyReceipt(service: AppleReceiptValidator.VerifyReceiptURLType = .production) {
              // 本地验证（SwiftyStoreKit 已经写好的类） AppleReceiptValidator
               // .production 苹果验证  .sandbox 本地验证
            let receipt = AppleReceiptValidator(service: service)
    //        let password = "公共秘钥"
            SwiftyStoreKit.verifyReceipt(using: receipt, completion: { (result) in
                switch result {
                case .success(let receipt):
                    let productId = self.curProduct.getString("PID")
                    // Verify the purchase of Consumable or NonConsumable
                    let purchaseResult = SwiftyStoreKit.verifyPurchase(
                        productId: productId ?? "",
                        inReceipt: receipt)
                        
                    switch purchaseResult {
                        case .purchased(let receiptItem):
                            print("\(String(describing: productId)) is purchased: \(receiptItem)")
                            let popup = PopupSureBox(title: "充值成功", sureText: "确定")
                            popup.show(vc: UIViewController.topMostController() ?? self)
                            popup.onSureButtonClick = {
                                self.popViewController()
                            }
                            MBProgressHUD.hideOrDecrease()
                        case .notPurchased:
                            print("The user has never purchased \(String(describing: productId))")
                            MBProgressHUD.hideOrDecrease()
                    }
                    break
                case .error(let error):
                 print("error--->\(error)")
                    break
                }
            })
        }
    
    @objc func onOKButtonClick(button: Button) {
        MBProgressHUD.showOrIncrease()
        payByID(ProductID: curProduct.getString("PID") ?? "")
    }
    
    //
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.row)
        curProduct = dataList[indexPath.row]
    }
    
    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    //UICollectionViewDelegate,UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AppPayCell
        let dic = dataList[indexPath.row]
        cell.celldata = dic
        return cell
    }
}
